package com.gzsxy.sso.core.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzsxy.sso.core.model.CustomUser;
import com.gzsxy.sso.core.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 登录成功自定义事件
 * @date 2021/11/10 21:01
 */

@Slf4j
@Component
public class AuthenticationSuccessHandlerImpl implements ApplicationListener<AuthenticationSuccessEvent> {

    private  final static String FORMAT = "yyyy-MM-dd HH:mm:ss";
    @Autowired
    private UserService userService;



    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        //这里的事件源除了登录事件（UsernamePasswordAuthenticationToken）还有可能是token验证事件源（OAuth2Authentication）
        if(!event.getSource().getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")){
            return ;
        }

        //这里还有oAuth2的客户端认证的事件，需要做一个判断
        if(event.getAuthentication().getDetails() != null){
            //登录日志逻辑。。。
            CustomUser userDetail = (CustomUser)event.getAuthentication().getPrincipal();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMAT);
            // 更新最后登录时间
//            userService.updateLastlogintime(userDetail.getId());
            log.info("用户[{}]于[{}]登录成功!", userDetail.getUsername(), simpleDateFormat.format(new Date()));

        }

    }
}
